﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.Data;
using System.Windows.Media.Imaging;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Controls;
using System.Globalization;
using produccion.modelo;
using produccion.AccesoDatos;
using produccion.clases;
using System.Windows.Input;
using System.Collections.Specialized;

namespace produccion.vistamodelo
{
    class VMMantenimientoConceptosFac : ViewModelBase
    {
        #region Campos

            private List<CLSCCPFAC> _lisconceptos = new List<CLSCCPFAC>();
            private ProcesoProduccionRepositorio _repositorio = new ProcesoProduccionRepositorio();

        #endregion

        #region Constructor

            public VMMantenimientoConceptosFac()
            {
                try
                {
                    consultarConceptosFac();
                    lisconceptosfac.CollectionChanged += OnCollectionChanged;

                    if (MDOgeneral.conexion == null || MDOgeneral.conexion.State == ConnectionState.Closed)
                    {
                        MDOgeneral.conectar();
                    }
                    strTituloVentana = "Mantenimiento de conceptos de facturación - Usuario: " + MDOgeneral.usuario + " - [frmMantenimientoConceptosFac]";
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

        #endregion

        #region Comandos

            RelayCommand _cmdSalir;
            public ICommand cmdSalir
            {
                get
                {
                    if (_cmdSalir == null)
                    {
                        _cmdSalir = new RelayCommand(Salir);
                    }
                    return _cmdSalir;
                }
            }

            RelayCommand _cmdEliminar;
            public ICommand cmdEliminar
            {
                get
                {
                    if (_cmdEliminar == null)
                    {
                        _cmdEliminar = new RelayCommand(x => eliminarConceptosFac());
                    }
                    return _cmdEliminar;
                }
            }

            RelayCommand _cmdGrabar;
            public ICommand cmdGrabar
            {
                get
                {
                    if (_cmdGrabar == null)
                    {
                        _cmdGrabar = new RelayCommand(x => grabarConceptosFac());
                    }
                    return _cmdGrabar;
                }
            }

        #endregion

        #region Propiedades
            private string _strTituloVentana;
            public string strTituloVentana
            {
                get { return _strTituloVentana; }
                set { _strTituloVentana = value; base.OnPropertyChanged("strTituloVentana"); }
            }

            public List<CLSCCPFAC> lisconceptos
            {
                get { return _lisconceptos; }
                set { _lisconceptos = value; base.OnPropertyChanged("lisconceptos"); }
            }

            private MDOgeneral.mensaje _msn = new MDOgeneral.mensaje();
            public MDOgeneral.mensaje msn
            {
                get { return _msn; }
                set { _msn = value; base.OnPropertyChanged("msn"); }
            }

            private ObservableCollection<VMConceptosdeFacturacion> _lisconceptosfac = new ObservableCollection<VMConceptosdeFacturacion>();
            public ObservableCollection<VMConceptosdeFacturacion> lisconceptosfac
            {
                get { return _lisconceptosfac; }
                set { _lisconceptosfac = value; base.OnPropertyChanged("lisconceptosfac"); }
            }

            private VMConceptosdeFacturacion _selconceptofac;
            public VMConceptosdeFacturacion selconceptofac
            {
                get { return _selconceptofac; }
                set { _selconceptofac = value; base.OnPropertyChanged("selconceptofac"); }
            }

            private Boolean _logValido;
            public Boolean logValido
            {
                get { return _logValido; }
                set { _logValido = value; base.OnPropertyChanged("logValido"); }
            }

        #endregion

        #region Metodos
            
            public void consultarConceptosFac()
            {
                try
                {
                    lisconceptos = new CLSCCPFAC().listarConceptosFac();
                    List<VMConceptosdeFacturacion> all = (from cf in lisconceptos select new VMConceptosdeFacturacion(cf)).ToList();
                    foreach (VMConceptosdeFacturacion con in all)
                    {
                        con.validarConcepto += validaConcepto;
                        con.PropertyChanged += OnPropertyChanged;
                    }
                    lisconceptosfac = new ObservableCollection<VMConceptosdeFacturacion>(all);
                    lisconceptosfac.CollectionChanged += OnCollectionChanged;
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                try
                {
                    logValido = ((from con in lisconceptosfac where con.IsValid.Equals(false) select con.IsValid).ToList().Count()) > 0 ? true : false;
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
            {
                try
                {
                    if (e.NewItems != null && e.NewItems.Count > 0)
                    {
                        foreach (VMConceptosdeFacturacion con in e.NewItems)
                        {
                            con.validarConcepto += validaConcepto;
                            con.PropertyChanged += OnPropertyChanged;
                        }
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            public string validaConcepto(string codccp)
            {
                try
                {
                    int i = (from con in lisconceptos where con.CODCCP_CFC.Equals(codccp.Trim()) select con).ToList().Count();
                    if (i > 1)
                    {
                        return "Concepto de facturación ya existe.";
                    }
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
                return null;
            }

            private void grabarConceptosFac()
            {
                try
                {
                    Mouse.OverrideCursor = Cursors.Wait;
                    List<CLSCCPFAC> lstAgregar = (from con in lisconceptosfac where con.agregar.Equals(true) select con.getConceptosFac()).ToList();
                    List<CLSCCPFAC> lstActualizar = (from con in lisconceptosfac where con.actualizar.Equals(true) select con.getConceptosFac()).ToList();
                    List<CLSCCPFAC> lstEliminar = (from con in lisconceptosfac where con.eliminar.Equals(true) select con.getConceptosFac()).ToList();

                    if (_repositorio.guardarConceptosFac(lstActualizar, lstEliminar, lstAgregar))
                    {
                        msn.texto = "La información se guardo con exito.";
                        msn.tipo = true;
                        consultarConceptosFac();
                    }
                    else
                    {
                        msn.texto = "La información de conceptos de facturación no se pudo grabar.";
                        msn.tipo = false;
                    }
                    Mouse.OverrideCursor = Cursors.Arrow;
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }

            public void eliminarConceptosFac()
            {
                try
                {
                    if (selconceptofac.agregar)
                        lisconceptosfac.Remove(selconceptofac);
                    else
                        selconceptofac.eliminar = !selconceptofac.eliminar;
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }
            public void Salir(object frmFormulario)
            {
                try
                {
                    ((Window)frmFormulario).Close();
                }
                catch (Exception ex) { MessageBox.Show(ex.Message); }
            }
        #endregion

    }

    #region Vistas-Model

    public class VMConceptosdeFacturacion : ViewModelBase, IDataErrorInfo
    {

        #region Campos

        private CLSCCPFAC _conceptosFac = new CLSCCPFAC();
        public delegate string validarConceptoFac(string codccp_cfc);

        #endregion

        #region Constructor

        public VMConceptosdeFacturacion(CLSCCPFAC conceptosFac)
        {
            _conceptosFac = conceptosFac;
        }

        public VMConceptosdeFacturacion()
        {
            agregar = true;
            base.OnPropertyChanged("codccp_cfc");
        }

        #endregion

        #region Metodos

        public CLSCCPFAC getConceptosFac()
        {
            return _conceptosFac;
        }

        #endregion

        #region Propiedades

        public validarConceptoFac validarConcepto;

        public string codccp_cfc
        {
            get { return _conceptosFac.CODCCP_CFC; }
            set 
            {
                if (agregar == true)
                {
                    _conceptosFac.CODCCP_CFC = value;
                    base.OnPropertyChanged("codccp_cfc");
                }
            }
        }

        public string nomccp_cfc
        {
            get { return _conceptosFac.NOMCCP_CFC; }
            set 
            {
                if (_conceptosFac.NOMCCP_CFC != value && agregar == false)
                    actualizar = true;
                _conceptosFac.NOMCCP_CFC = value;
                base.OnPropertyChanged("nomccp_cfc");
            }
        }

        public string ctacon_cfc
        {
            get { return _conceptosFac.CTACON_CFC; }
            set 
            {
                if (_conceptosFac.CTACON_CFC != value && agregar == false)
                    actualizar = true; 
                _conceptosFac.CTACON_CFC = value;
                base.OnPropertyChanged("ctacon_cfc"); 
            }
        }

        public string ctaiva_cfc
        {
            get { return _conceptosFac.CTAIVA_CFC; }
            set 
            {
                if (_conceptosFac.CTAIVA_CFC != value && agregar == false)
                    actualizar = true; 
                _conceptosFac.CTAIVA_CFC = value;
                base.OnPropertyChanged("ctaiva_cfc"); 
            }
        }

        public string ctactp_cfc
        {
            get { return _conceptosFac.CTACTP_CFC; }
            set 
            {
                if (_conceptosFac.CTACTP_CFC != value && agregar == false)
                    actualizar = true; 
                _conceptosFac.CTACTP_CFC = value;
                base.OnPropertyChanged("ctactp_cfc"); }
        }

        public string ivacon_cfc
        {
            get { return _conceptosFac.IVACON_CFC; }
            set 
            {
                if (_conceptosFac.IVACON_CFC != value && agregar == false)
                    actualizar = true;
                _conceptosFac.IVACON_CFC = value;
                base.OnPropertyChanged("ivacon_cfc"); 
            }
        }

        public string rtecon_cfc
        {
            get { return _conceptosFac.RTECON_CFC; }
            set 
            {
                if (_conceptosFac.RTECON_CFC != value && agregar == false)
                    actualizar = true; 
                _conceptosFac.RTECON_CFC = value;
                base.OnPropertyChanged("rtecon_cfc"); 
            }
        }

        public Int32 basrte_cfc
        {
            get { return _conceptosFac.BASRTE_CFC; }
            set 
            {
                if (_conceptosFac.BASRTE_CFC != value && agregar == false)
                    actualizar = true; 
                _conceptosFac.BASRTE_CFC = value;
                base.OnPropertyChanged("basrte_cfc"); 
            }
        }

        public double porrte_cfc
        {
            get { return _conceptosFac.PORRTE_CFC; }
            set 
            {
                if (_conceptosFac.PORRTE_CFC != value && agregar == false)
                    actualizar = true; 
                _conceptosFac.PORRTE_CFC = value;
                base.OnPropertyChanged("porrte_cfc"); 
            }
        }

        private bool _actualizar = false;
        public bool actualizar
        {
            get { return _actualizar; }
            set
            {
                _actualizar = value; base.OnPropertyChanged("actualizar");
            }
        }

        private bool _eliminar = false;
        public bool eliminar
        {
            get { return _eliminar; }
            set { _eliminar = value; base.OnPropertyChanged("eliminar"); }
        }

        private bool _agregar = false;
        public bool agregar
        {
            get { return _agregar; }
            set { _agregar = value; base.OnPropertyChanged("agregar"); }
        }

        #endregion

        #region IDataErrorInfo Members

        string IDataErrorInfo.Error { get { return null; } }

        string IDataErrorInfo.this[string propertyName]
        {
            get { return this.GetValidationError(propertyName); }
        }

        #endregion

        #region Validation

        /// <summary>
        /// Returns true if this object has no validation errors.
        /// </summary>
        /// 

        public bool IsValid
        {
            get
            {
                foreach (string property in ValidatedProperties)
                    if (GetValidationError(property) != null)
                        return false;
                return true;
            }
        }

        static readonly string[] ValidatedProperties = 
        { 
            "codccp_cfc",
            "nomccp_cfc",
            "ctacon_cfc",
            "ctaiva_cfc",
            "ctactp_cfc",
            "ivacon_cfc",
            "rtecon_cfc"
        };

        string GetValidationError(string propertyName)
        {
            if (Array.IndexOf(ValidatedProperties, propertyName) < 0)
                return null;

            string error = null;

            switch (propertyName)
            {
                case "codccp_cfc":
                    error = Validatecodigo();
                    break;
                case "nomccp_cfc":
                    error = this.ValidateNombre();
                    break;
                case "ctacon_cfc":
                    error = this.ValidateCuentaCon();
                    break;
                case "ctaiva_cfc":
                    error = this.ValidateCuentaIva();
                    break;
                case "ctactp_cfc":
                    error = this.ValidateCuentaCtp();
                    break;
                case "ivacon_cfc":
                    error = this.ValidateIva();
                    break;
                case "rtecon_cfc":
                    error = this.ValidateRet();
                    break;
                //case "porrte_cfc":
                //    error = this.Validateporrte_cfc();
                //    break;
                //case "basrte_cfc":
                //    error = this.Validatebasrte_cfc();
                //    break;
                default:
                    Debug.Fail("Unexpected property being validated on Customer: " + propertyName);
                    break;
            }
            return error;
        }

        string Validatecodigo()
        {
            try
            {
                if (codccp_cfc == null) { return "Debe ingresar el código del concepto de facturación."; }
                if (codccp_cfc.Length > 2) { return "El código del concepto de facturación no puede tener mas de 2 caracteres"; }
                if (codccp_cfc == null)
                {
                    string error = null;
                    error = validarConcepto(codccp_cfc);
                    if (!String.IsNullOrEmpty(error))
                    {
                        return error;
                    }
                }
                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        string ValidateNombre()
        {
            try
            {
                if (nomccp_cfc == null) { return "Debe ingresar el nombre del concepto de facturación"; }
                if (nomccp_cfc.Length > 40) { return "El nombre del codigo no puede tener mas de 40 caracteres"; }

                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        string Validatebasrte_cfc()
        {
            try
            {
                //if (basrte_cfc == null) { basrte_cfc = 0; }
                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }
        string Validateporrte_cfc()
        {
            try
            {
                //if (porrte_cfc == null) { porrte_cfc = 0; }
                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }


        string ValidateCuentaCon()
        {
            try
            {
                if (ctacon_cfc == null) { ctacon_cfc = " "; }
                //if (ctacon_cfc.Length > 10) { return "La cuenta contable no puede tener mas de 10 caracteres"; }

                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        string ValidateCuentaIva()
        {
            try
            {
                if (ctaiva_cfc == null) { ctaiva_cfc = " "; }
                //if (ctaiva_cfc.Length > 10) { return "La cuenta de Iva no puede tener mas de 10 caracteres"; }

                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        string ValidateCuentaCtp()
        {
            try
            {
                if (ctactp_cfc == null) { ctactp_cfc = " "; }
                //if (ctactp_cfc.Length > 10) { return "La cuenta contrapartida no puede tener mas de 10 caracteres"; }

                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        string ValidateIva()
        {
            try
            {
                if (ivacon_cfc == null) { return "Debe especificar si tiene iva o no"; }
                if (ivacon_cfc.Length > 1) { return "Debe ingresar una sola letra"; }

                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        string ValidateRet()
        {
            try
            {
                if (rtecon_cfc == null) { return "Debe especificar si tiene retención o no"; }
                if (rtecon_cfc.Length > 10) { return "Debe ingresar una sola letra"; }

                return null;
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
            return null;
        }

        #endregion
    }

    #endregion

}
